<?php

/**
 * @package mikrokosmos
 * mk generic utilities library file created on  nov-2004
 * jaco_at_pixeldump_dot_org
 */



/**
 * private
 * delete all tmp in SERVER_MKTMP directory
 */
function purge_cache(){

	global $mkConfig;

	$h = opendir($mkConfig["tmp"]);

	while (false !== ($file = readdir($h))) {
		if ($file != "." && $file != "..") {
		    unlink($mkConfig["tmp"] .$file);
		}
	}

	closedir($h);
}

/**
 * set/get global debug mode
 */
function set_debugMode($dMode = DEBUG_MODE_NONE){
	global $debugMode;
	$debugMode = $dMode;
}
function get_debugMode() {
	global $debugMode;
	return $debugMode;
}

/**
 * generic
 * retrieve a whole list of files with ext in a given directory
 */
function get_fileList($dir, $ext, $orderByTime = true){

	$fileList = array();
	$files = array();
	$h = opendir($dir);
	$extAr = array();

	$lastDCH = substr($dir, -1);
	if($lastDCH != "/" || $lastDCH != "\\") $dir .= "/";

	if(!is_array($ext)) $extAr = array($ext);
	else $extAr = $ext;

	foreach($extAr as $iExt){

		$iExt = strtoupper($iExt);

		if($iExt[0] != ".") $iExt = "." .$iExt;

		while (false !== ($file = readdir($h))) {

    	 	if($file == '.' || $file == '..')	continue;

			$rext = strtoupper(substr($file, strlen($file) - strlen($iExt)));

			if(!(strcasecmp($rext, $iExt))){

				$localpath = $dir .$file;

				if (is_file($localpath)) {
					$key = filemtime($localpath).md5($file);
       				$files[$key] = $file;
				}
			}
		}
		ksort($files);
		rewinddir($h);
	}
	closedir($h);

	foreach($files as $k => $v) $fileList[] = $v;

	if($orderByTime) return array_reverse($fileList);
	sort($fileList, SORT_STRING);

	return $fileList;
}

/**
 * generic: converts number to a fixed length hex string
 */
function get_fixedHex($nmb, $wd){ return sprintf("%0{$wd}X", $nmb); }

/**
 * private:
 * builds and returns
 * initial row white character from a given tabLevel
 * e.g: tabLevel = 3
 * returns: \r\n\t\t\t
 */
function get_xml_indent_row($tabLevel){
	return "\r\n" .str_repeat("\t", $tabLevel);
}

/**
 * private builds and returns
 * a string of n &nbsp; for html indentation
 */
function get_html_indent_row($spLevel){ return str_repeat(SP, $spLevel); }

// ----------------------- x debug purpose
/**
 * private:
 * output a var value and a msg to the browser
 */
function trace_var($tvar, $msg = "", $nobr = false, $noddot = false){

	$dm = get_debugMode();

	if($dm == DEBUG_MODE_NONE) return false;

	$str = "";

	$pfx = ($nobr) ? " " : BR;
	$ddot = $noddot ? "" : ": ";


	if(!is_array($tvar) && !is_object($tvar)) {
		if(!strlen($tvar) && !strlen($msg) && !$nobr) $str = BR;
		else $str = $pfx .$msg .$ddot .$tvar;
	}

	log_write_entry($str);

	if($dm & DEBUG_MODE_BROWSER) echo $str;
	if($dm & DEBUG_MODE_RETURN) return $str;
}


/**
 * private:
 * output var value from its name
 * NOTE: it works only at main level (not in function calls)
 */
function trace_from_name($varname, $msg = "", $nobr = false, $noddot = false){
	global ${$varname};
	$msg = strlen($msg) ? $varname ." " .$msg : $varname;
	return trace_var(${$varname}, $msg, $nobr, $noddot);
}

/**
 * private:
 * output associative data members and keys
 */
function trace_array_assoc($ar, $label = "", $delimiters = true, $pfx = 0){

	if($delimiters) trace_var("____" .$label ." _______________________", "", false, true);

	foreach($ar as $k => $v){
		if(is_array($v) || is_object($v)) trace_array_assoc($v, "|__ " .$k, false, $pfx + 4);
		else trace_var(str_repeat(SP, $pfx) .$v, $k);
	}

	if($delimiters) trace_var("____end of: " .$label ." _______________________", "", false, true);
}


/**
 * delete log file an create empty new
 */
function log_reset(){

	if(file_exists(MK_LOG))
		unlink(MK_LOG);

	$log = fopen(MK_LOG, "w");
	fclose($log);
}


/**
 * add log entry
 */
function log_write_entry($logEntry){

	if(!(get_debugMode() & DEBUG_MODE_LOG)) return;

	$log = fopen(MK_LOG, "a");
	$logEntry .= "\r\n";

	fwrite($log, $logEntry, strlen($logEntry));
	fclose($log);
}

/**
 * view log on browser
 */
function log_view(){
	if(file_exists(MK_LOG)){
		echo file_get_contents(MK_LOG);
	}
}

/**
 * private:
 * get date of dev log
 */
 function get_devlog_date($dvPath){

 	if(file_exists($dvPath)){
 		return date("F j Y", filemtime($dvPath));
 	}

 }


/**
 * private
 * return image list in SERVER_MKIMGS
 */
 function get_image_list(){
	$imageList = array();

	$tmpIL = get_fileList(SERVER_MKIMGS, array("jpg", "png"));

	foreach($tmpIL as $imgFN){

		$ilCount = count($imageList);
		$imageList[$ilCount] = array();
		$imageList[$ilCount]["imgFN"] = $imgFN;
		$imageList[$ilCount]["imgidx"] = $ilCount;
	}

	$k = 0;
	foreach($imageList as $imgObj){

		$fn = $imgObj["imgFN"];
		$bs = getimagesize(SERVER_MKIMGS. $fn);
		$imageList[$k]["imgWidth"] = $bs[0];
		$imageList[$k++]["imgHeight"] = $bs[1];
	}

	return $imageList;
}

/**
 * generic
 * read bin data
 * return a string width hex data formatted as in hex editor
 */
function hex_dump($binData, $nobr = false){

	$dLength = strlen($binData);
	$hexStr = "";
	for($i = 0; $i < $dLength; $i++){

		if($i && !($i % 16)) $hexStr .= ($nobr) ? "" : "<br />";

		//$hex = dechex(ui8dec($binData[$i]));
		//if(strlen($hex) < 2) $hex = "0" .$hex;
		$hexStr .= get_bytehex(ui8dec($binData[$i])) ." ";
	}

	return $hexStr;
}


// return a file name from script file name
// e.g.: http://path/to/test01.php become test01.swf
function get_swf_from_basename($path){
	return basename($path, ".php") ."swf";
}


// DRAW SUPPORT


/*
 * generic, used in test context
 * return an array containing x and y random values
 */
function get_random_coords($cMin = 0, $cMax = 550){
	$coord = array();
	$coord["x"] = rand($cMin, $cMax);
	$coord["y"] = rand($cMin, $cMax);

	return $coord;
}


/*
 * generic, used in test context
 * return an array containing
 * red, green and blue random values
 */
function get_random_color($cMin = 0, $cMax = 0xff, $includeAlpha = true){

	$cAr = array();
	$cAr["red"] = rand($cMin, $cMax);
	$cAr["green"] = rand($cMin, $cMax);
	$cAr["blue"] = rand($cMin, $cMax);
	if($includeAlpha) $cAr["alpha"] = rand($cMin, $cMax);

	return $cAr;
}

/**
 * populate postData in an associative array with some
 * features (id, page default value)
 * for me is smarter than using _SERVER or _POST and so on
 */
function get_postData(){

	$postData = array();

	if(count($_POST))
		foreach($_POST as $k => $v) $postData[$k] = $v;

	// index for pagination
	if(isset($_GET["page"])) $postData["page"] = $_GET["page"];
	if(!isset($_POST["page"])) $postData["page"] = 0;

	// id of current record (edit, delete and so on)
	if(isset($_GET["id"]))
		if(!isset($postData["id"])) $postData["id"] = $_GET["id"];

	return $postData;
}

/**
 * generic
 * center html content [scriptname] in a web page
 */
function show_centered_content($content = "", $scriptFN = ""){

	$str = "";                                                // will contain some content
	if(strlen($scriptFN)) $str .= "<h2>" .$scriptFN ."</h2>"; // write a title
	$str .= $content;                                         // complete content population

	$div = new MKDiv();                                       // bound in a layer
	$div->add_divAttrib("STYLE", "text-align:left");          // natural text flow
	$div->set_content($str);                                  //

	$sHtml = get_page_header();                               // prepare an html page header

	$tbl = new MKTable();                                     // new html table
	$tbl->add_tableAttrib("WIDTH", "100%");                   // populate with attribs ...
	$tbl->add_tableAttrib("HEIGHT", "100%");                  // ... full client area

	$tRow = array();                                          // prepare an array ...
	$tRow[0] = array();                                       // ... first "cell"
	$tRow[0]["cellContent"] = $div->fetch_html();             // ... populate cell
	$tRow[0]["cellAttribs"]["ALIGN"] = "center";              // center in cell
	$tRow[0]["cellAttribs"]["VALIGN"] = "middle";             // ...
	$tbl->add_row($tRow);

	$sHtml .= $tbl->fetch_html();                             // get almost the whole html content
	$sHtml .= "</body></html>";                               // close html tags

	return $sHtml;                                            // return to caller
}

// ------------------------------------- end of mk_utils
?>
